package cn.edu.cimv.service.impl;

import cn.edu.cimv.pojo.PaperCallBack;
import cn.edu.cimv.service.UploadService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 上传控件
 * Created by 门铎 on 2016/8/10.
 */
@Service
public class UploadServiceImpl implements UploadService {
    private static final Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);
    @Autowired PaperCallBack paperCallBack;
    /**
     * 图片上传到upload/pic目录
     * @param pic 图片二进制文件
     * @return 图片名
     */
    @Override
    public String uploadPic(MultipartFile pic,String path) {
        //图片路径+图片名
        String realPath = path  + "upload/pic/" ;
        String prefix = "." + getPrefix(pic);
        String url = realPath +  System.currentTimeMillis()+""+Math.round(Math.random() * 1000) + prefix;
        File file = upload(url,pic);
        //返回图片名
        return  file.getName().substring(file.getName().lastIndexOf("/")+1);
    }

    @Override
    public PaperCallBack uploadPdf(MultipartFile pdf, String path) {

        paperCallBack.setRealName(pdf.getOriginalFilename());
        //pdf路径+论文名
        String realPath = path  + "upload/pdf/" ;
        String prefix = "." + getPrefix(pdf);
        String url = realPath +  System.currentTimeMillis()+""+Math.round(Math.random() * 1000) + prefix;
        //上传文件
        File file = upload(url,pdf);
        //返回论文
        paperCallBack.setUrlName(file.getName().substring(file.getName().lastIndexOf("/")+1));
        return  paperCallBack;
    }

    @Override
    public String uploadTou(MultipartFile tou, String path) {
        //图片路径+图片名
        String realPath = path  + "upload/tou/" ;
        String prefix = "." + getPrefix(tou);
        String url = realPath +  System.currentTimeMillis()+""+Math.round(Math.random() * 1000) + prefix;
        File file = upload(url,tou);
        //返回图片名
        return  file.getName().substring(file.getName().lastIndexOf("/")+1);
    }

    private String getPrefix(MultipartFile file){
        String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        System.out.println(prefix);
        return prefix;
    }

    private File upload(String url,MultipartFile ofile){
        File file  =new File(url);
        if(!ofile.isEmpty()){
            logger.info("开始上传文件" + ofile.getName());

            try {
                FileUtils.copyInputStreamToFile(ofile.getInputStream(),file);
            } catch (IOException e) {
                logger.error("上传文件错误:{}" + "文件上传路径" + file.getAbsolutePath(),e.getMessage());
                e.printStackTrace();
            }
        }
        return file;
    }
}


